package com.xxx.system.service.impl;


import com.github.pagehelper.PageHelper;
import com.xxx.system.domain.Role;
import com.xxx.system.mapper.RoleMapper;
import com.xxx.system.query.RoleQuery;
import com.xxx.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
// 查询事务控制方式：设置只读 支持当前事务，如果没有当前事务，就以非事务方法执行。
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void addRole(Role role) {
        roleMapper.addRole(role);
        //添加员工时,通过xml语句里面配置uk,使得id插入到员工角色中
        //定义方法把员工的id和角色id的集合插入到中间表当中以便展示
        if(role.getPerms().size()>0){//维护角色与权限
            roleMapper.addRoleAndPs(role);
        }
        if(role.getMenus().size()>0){}
            roleMapper.addRoleAndMs(role);
    }

    @Override
    @Transactional
    public void updateRole(Role role) {
        roleMapper.updateRole(role);
        //修改,先根据id删除,在添加
        roleMapper.delRoleAndPs(role.getId());
        roleMapper.delRoleAndMs(role.getId());
        //添加
        if(role.getPerms().size()>0){//维护角色与权限
            roleMapper.addRoleAndPs(role);
        }
        if(role.getMenus().size()>0){//维护角色与菜单
        roleMapper.addRoleAndMs(role);
        }
    }

    @Override
    @Transactional
    public void deteleById(Long id) {
        roleMapper.deteleById(id);
        //删除中间两个维护的表
        roleMapper.delRoleAndPs(id);
        roleMapper.delRoleAndMs(id);
    }

    @Override
    public Role findOne(Long id) {
        return roleMapper.findOne(id);
    }

    @Override
    public List<Role> findAll() {
        return roleMapper.findAll();
    }

    @Override
    public List<Role> queryPage(RoleQuery roleQuery) {
        //开始设置分页信息
        //干了三件事情：
        //1.查询总条数 2.根据驱动名称自动添加分页 3.分页查询返回结果
        PageHelper.startPage(roleQuery.getCurrentPage(), roleQuery.getPageSize());
        //直接高级查询，自动实现分页
        List<Role> roles = roleMapper.queryPage(roleQuery);
        //遍历,添加元素1.权限id集合---2. 菜单id集合
        for (Role role : roles) {
            List<Long> perms=roleMapper.findPs(role.getId());
            role.setPerms(perms);

            List<Long> menus=roleMapper.findMs(role.getId());
            role.setMenus(menus);
        }
        return roles;
    }

    @Override
    @Transactional
    public void deleteRoleByIds(Long[] ids) {
        roleMapper.deleteRoleByIds(ids);
        //批量删除两个维护的表
        roleMapper.delPatchRoleAndPs(ids);
        roleMapper.delPatchRoleAndMs(ids);
    }
}
